package com.sdy.healthcode.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.EncodeUtil;
import com.sdy.common.utils.RandomUtil;
import com.sdy.healthcode.biz.constants.Constants;
import com.sdy.healthcode.biz.mapper.BayonetManageMapper;
import com.sdy.healthcode.biz.model.BayonetManage;
import com.sdy.healthcode.biz.service.BayonetManageService;
import com.sdy.healthcode.biz.utils.QrCodeUtil;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cgj
 * @since 2020-03-09
 */
@Slf4j
@Service
public class BayonetManageServiceImpl extends BaseServiceImpl<BayonetManage> implements BayonetManageService {
    @Autowired
    private BayonetManageMapper bayonetManageMapper;
    @Autowired
    private BayonetManageService bayonetManageService;

    @Override
    public Boolean saveBayonet(Integer userId, BayonetManage bayonetManage, String domain) {
        String tk = "0002" + UUID.randomUUID().toString().replace("-", "")
                + EncodeUtil.md5(System.currentTimeMillis() + "").substring(0, 8);
        // 创建用户QR文件夹
        String folderDir = Constants.QRCODE_PATH_BAYONET;
        File dir = new File(folderDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = folderDir + "/" + System.currentTimeMillis() + "_" + RandomUtil.produceNumber(5) + "." + Constants.QRCODE_FORMAT;
        bayonetManage.setCreateUser(userId).setCreateTime(new Date()).setState(1).setBayonetToken(tk).setQrpicturePath(filePath);
        boolean result = bayonetManageService.save(bayonetManage);

        // 创建二维码
        createBayonetCode(bayonetManage, domain);
        return result;
    }

    @PostConstruct
    public void init() {
        // 初始化创建二维码存储文件夹
        File dir = new File(Constants.QRCODE_PATH_BAYONET);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 生成二维码信息
     */
    private boolean createBayonetCode(BayonetManage bayonetManage, String domain) {
        // 创建用户QR文件夹
        String folderDir = Constants.QRCODE_PATH_BAYONET;
        File dir = new File(folderDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = bayonetManage.getQrpicturePath();
        String content = domain + "/scanCodeInOut?tk=" + bayonetManage.getBayonetToken();
        createQrCode(null, content, filePath);
        // 保存新的健康码
        return true;
    }

    /**
     * 创建二维码
     */
    private void createQrCode(Color color, String content, String filePath) {
        log.info("生成二维码，内容：" + content);
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            QrCodeUtil.createQrCode(
                    Constants.QRCODE_FORMAT,
                    fos,
                    content,
                    color,
                    Color.WHITE,
                    null,
                    Constants.QRCODE_SIZE);
        } catch (Exception e) {
            String err = "二维码生成失败,请稍后再试!";
            log.error(err, e);
            File f = new File(filePath);
            if (f.exists()) {
                f.delete();
            }
            throw new RuntimeException(err);
        }
    }


}
